/**
 * @Author: Sagan
 * @Date: 2020/09/19 18:23
 */
package function

import (
	"gitee.com/big_meteor/godash/number"
	"reflect"
	"strconv"
)

func ToFloat64(v interface{}) (float64, bool) {
	rt := reflect.TypeOf(v)

	if nil == rt {
		return 0, false
	}

	rv := reflect.ValueOf(v)

	if reflect.Ptr == rv.Kind() {
		rv = rv.Elem()
	}

	var kind = rv.Kind()
	switch kind {
	case reflect.Float32, reflect.Float64:
		return rv.Float(), true
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return float64(rv.Int()), true
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return float64(rv.Uint()), true
	}

	if reflect.String == kind && number.IsNum(rv.String()) {
		v, err := strconv.ParseFloat(rv.String(), 64)

		if nil != err {
			return 0, false
		}

		return v, true
	}

	return 0, false
}
